package com.yao.grpcdemo.grpc;

import io.grpc.BindableService;
import io.grpc.ServerBuilder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

/**
 * 1.扫描@GRpcService标注的类，容器会创建该类的对象
 * 2.将@GRpcService标注的类对象绑定到GRpcServer
 *
 * @author yys1892
 */
public class GRpcServiceBeanPostProcessor implements BeanPostProcessor, BeanDefinitionRegistryPostProcessor {
    private ConfigurableListableBeanFactory beanFactory;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof  BindableService) {
            ServerBuilder builder = beanFactory.getBean(ServerBuilder.class);
            builder.addService((BindableService) bean);
        }
        return bean;
    }



    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(registry);
        classPathBeanDefinitionScanner.setBeanNameGenerator(new AnnotationBeanNameGenerator());
        classPathBeanDefinitionScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcService.class));
        classPathBeanDefinitionScanner.scan("com.yao.grpcdemo");
    }
}
